// src/pages/Login.jsx
import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Form, Input, Button, Toast, NavBar } from 'antd-mobile';
import { motion } from 'framer-motion';
import { useAuthStore } from '../store/authStore';
import { fadeIn } from '../styles/animations';
import { validateEmail, validatePassword } from '../utils/validation';

const Login = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { login, isAuthenticated, loading, error, clearErrors } = useAuthStore();
  const [formError, setFormError] = useState('');
  
  // If user is already authenticated, redirect to main page
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/wu', { replace: true });
    }
  }, [isAuthenticated, navigate]);
  
  // Show error message if login fails
  useEffect(() => {
    if (error) {
      Toast.show({
        content: error,
        position: 'center',
      });
      clearErrors();
    }
  }, [error, clearErrors]);
  
  const onFinish = async (values) => {
    setFormError('');
    
    try {
      const emailValid = validateEmail(values.email);
      const passwordValid = validatePassword(values.password);
      
      if (!emailValid) {
        setFormError('请输入有效的邮箱地址');
        return;
      }
      
      if (!passwordValid) {
        setFormError('密码至少需要6位字符');
        return;
      }
      
      await login(values.email, values.password);
      // Login successful, redirect will be handled by useEffect
    } catch (err) {
      console.error('Login error:', err);
    }
  };
  
  return (
    <motion.div 
      className="flex flex-col bg-white mobile-container"
      style={{
        height: '100vh',
        overflow: 'hidden',
      }}
      initial="hidden"
      animate="visible"
      exit="exit"
      variants={fadeIn}
    >
      {/* <NavBar back={null} className="mobile-safe-area">登录</NavBar> */}
      
      <div 
        className="flex-grow flex flex-col justify-center mobile-scroll"
        style={{
          padding: '0.2rem',
          height: 'calc(100vh - 0.4rem)',
          overflowY: 'auto',
          overflowX: 'hidden',
        }}
      >
      
      <div className="w-full max-w-[2.5rem] mx-auto">
          <h9 className="text-center text-[0.28rem] font-bold text-gray-900">
            登录
          </h9>
        </div>
        <div className="mt-[0.3rem] w-full max-w-[2.5rem] mx-auto">
        
          <div className="bg-white py-[0.3rem] px-[0.15rem]">
            {formError && (
              <div className="mb-[0.15rem] text-red-500 text-[0.16rem] text-center" style={{ color: '#EF4444' }}>
                {formError}
              </div>
            )}
            
            <Form
              form={form}
              layout="vertical"
              onFinish={onFinish}
              footer={
                <Button 
                  block 
                  type="submit" 
                  color="primary" 
                  loading={loading} 
                  size="mini"
                  className="mt-[0.25rem]"
                  style={{ fontSize: '0.24rem', height: '0.6rem' }}
                >
                  登录
                </Button>
              }
            >
              <Form.Item
                name="email"
                label="邮箱"
                style={{ 
                  height: '1.7rem',
                  marginBottom: '0.15rem'
                }}
                rules={[{ required: true, message: '请输入邮箱' }]}
              >
                <Input 
                  placeholder="请输入邮箱" 
                  style={{ 
                    fontSize: '0.16rem',
                    height: '0.5rem',
                    padding: '0.1rem 0.15rem'
                  }} 
                />
              </Form.Item>
              
              <Form.Item
                name="password"
                label="密码"
                style={{ 
                  height: '1.7rem',
                  marginBottom: '0.15rem'
                }}
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input 
                  placeholder="请输入密码" 
                  type="password" 
                  style={{ 
                    fontSize: '0.16rem',
                    height: '0.5rem',
                    padding: '0.1rem 0.15rem'
                  }} 
                />
              </Form.Item>
              
            </Form>
            <div className="mt-[0.25rem] text-center">
              <Link 
                to="/register" 
                className="text-blue-500 hover:text-blue-700 text-[0.16rem]"
              >
                没有账号？立即注册
              </Link>
            </div>
            
          
          </div>
        </div>
      </div>
    </motion.div>
  );
};

export default Login;